package com.hundsun.cprs.yyt.service.trade.service.impl;

import com.hundsun.cprs.yyt.common.base.BaseService;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.service.common.Constants;
import com.hundsun.cprs.yyt.service.trade.dao.EntrustAuditLogDao;
import com.hundsun.cprs.yyt.service.trade.dao.TradeEntrustDao;
import com.hundsun.cprs.yyt.service.trade.domain.EntrustAuditLog;
import com.hundsun.cprs.yyt.service.trade.domain.TradeEntrust;
import com.hundsun.cprs.yyt.service.trade.domain.query.EntrustAuditLogQuery;
import com.hundsun.cprs.yyt.service.trade.dto.AuditRequest;
import com.hundsun.cprs.yyt.service.trade.service.EntrustAuditLogService;
import com.hundsun.cprs.yyt.service.trade.service.TradeEntrustService;
import com.hundsun.cprs.yyt.util.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;

/**
 * 挂售单批量导入审核处理接口
 * @author herong22384
 * @date 2019/8/14 19:11
 */
@Service
public class EntrustAuditLogServiceImpl extends BaseService implements EntrustAuditLogService {

    public static final String YYT_BATCH_AUDIT_LOCK = Constants.YYT_BATCH_AUDIT_LOCK;

    @Autowired
    private EntrustAuditLogDao auditLogDao;
    @Autowired
    @Qualifier("commonThreadPool")
    private Executor executor;
    @Autowired
    private TradeEntrustDao entrustDao;
    @Autowired
    private TradeEntrustService entrustService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void queryByPage(EntrustAuditLogQuery query) {
        List<EntrustAuditLog> entrustAuditLogs = auditLogDao.queryByPage(query);
        query.compatible(entrustAuditLogs);
    }

    @Override
    public void batchInsert(List<EntrustAuditLog> datas) {
        if (!CollectionUtils.isEmpty(datas)){
            auditLogDao.batchInsert(datas);
        }
    }

    @Override
    public void handleBatchAudit() {
        //异步处理导入记录
        executor.execute(new Runnable() {
            public void run() {
                try{
                    while (true){
                        EntrustAuditLogQuery query = new EntrustAuditLogQuery();
                        query.setStatus(0);
                        query.setPageNo(1);
                        query.setPageSize(200);
                        queryByPage(query);

                        if (query.getTotalCount() == 0){
                            break;
                        }

                        //更新该批数据状态为处理中
                        auditLogDao.updateStatusByBatch(query.getData(), 1,"处理中");

                        //处理批量审核导入
                        doBatchAuditImport(query.getData());
                    }
                }finally {
                    //释放redis锁
                    redisTemplate.delete(YYT_BATCH_AUDIT_LOCK);
                }
            }
        });
    }

    protected void  doBatchAuditImport(List<EntrustAuditLog> datas){
        List<EntrustAuditLog> logs = new ArrayList<>();
        for (EntrustAuditLog log : datas){
            try{
                //1.按导入的搜索条件查找对应的挂售单
                AuditRequest request = BeanUtils.transfrom(AuditRequest.class,log);
                List<TradeEntrust> entrusts = entrustDao.getAuditListByQuery(request);
                if (CollectionUtils.isEmpty(entrusts)){
                    log.setStatus(-1);
                    log.setRemark("未找到匹配的挂售单");
                    auditLogDao.updateByPrimaryKeySelective(log);
                    continue;
                }
                //2.挂售单审核上报
                for (TradeEntrust entrust : entrusts){
                    entrustService.entrust(entrust);
                }
                log.setStatus(2);
                log.setRemark("成功匹配挂售单："+entrusts.size()+"个");
                logs.add(log);
            }catch (ServiceCodeException e){
                logger.error(e);
                log.setStatus(-1);
                log.setRemark(e.getErrorDesc());
                auditLogDao.updateByPrimaryKeySelective(log);
            }catch (Exception e){
                logger.error(e);
                log.setStatus(-1);
                log.setRemark(e.getMessage());
                auditLogDao.updateByPrimaryKeySelective(log);
            }
        }
        if (!CollectionUtils.isEmpty(logs)){
            //批量更新审核记录
            auditLogDao.batchUpdate(logs);
        }
    }
}
